package netty.dubboRPC.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


/**
 * @ClassName NettyServer
 * @Description TODO
 * @Author director吴
 * @Date 2022/5/18 13:20
 * @Version 1.0
 **/
public class NettyServer {


    //对外暴露一个启动的方式
    public static void startServer(String hostName,int port){

        startServer0(hostName,port);


    }



    //编写一个初始化Netty Server和启动
    private static void startServer0(String hostName,int port){

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGrop = new NioEventLoopGroup();

        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGrop)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new NettyServerHandler());

                        }
                    });

            ChannelFuture future = bootstrap.bind(hostName, port).sync();
            System.out.println("服务提供者开始提供服务");
            future.channel().closeFuture().sync();


        }catch (Exception e){

            e.printStackTrace();

        }finally {

            bossGroup.shutdownGracefully();
            workGrop.shutdownGracefully();

        }


    }





}
